from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import func as db_func
from typing import List, Optional
from datetime import datetime

from api import deps
from models.exception_log import ExceptionLog
from schemas.exception_log import ExceptionLogCreate, ExceptionLogUpdate, ExceptionLogResponse, ExceptionLogListResponse

router = APIRouter()


@router.post("", response_model=ExceptionLogResponse, summary="创建异常日志")
def create_exception_log(
    exception_log: ExceptionLogCreate,
    db: Session = Depends(deps.get_db),
    current_user: dict = Depends(deps.get_current_active_user)
):
    """
    创建新的异常日志记录
    """
    db_exception_log = ExceptionLog(**exception_log.model_dump())
    db.add(db_exception_log)
    db.commit()
    db.refresh(db_exception_log)
    
    # 将数据库模型转换为Pydantic可接受的格式
    log_dict = {
        "id": db_exception_log.id,
        "exception_type": db_exception_log.exception_type,
        "exception_level": db_exception_log.exception_level,
        "title": db_exception_log.title,
        "description": db_exception_log.description,
        "drone_id": db_exception_log.drone_id,
        "task_id": db_exception_log.task_id,
        "detection_log_id": db_exception_log.detection_log_id,
        "location": db_exception_log.location,
        "responsible_user_id": db_exception_log.responsible_user_id,
        "status": db_exception_log.status,
        "resolution_description": db_exception_log.resolution_description,
        "created_at": db_exception_log.created_at,
        "updated_at": db_exception_log.updated_at,
        "resolution_time": db_exception_log.resolution_time,
        "responsible_user": None,
        "drone": None,
        "task": None
    }
    
    return log_dict


@router.get("", response_model=ExceptionLogListResponse, summary="获取异常日志列表")
def get_exception_logs(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(100, ge=1, le=1000, description="返回记录数"),
    exception_type: Optional[str] = Query(None, description="异常类型筛选"),
    exception_level: Optional[str] = Query(None, description="异常级别筛选"),
    status: Optional[str] = Query(None, description="处理状态筛选"),
    drone_id: Optional[int] = Query(None, description="无人机ID筛选"),
    task_id: Optional[int] = Query(None, description="任务ID筛选"),
    responsible_user_id: Optional[int] = Query(None, description="责任人ID筛选"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    db: Session = Depends(deps.get_db),
    current_user: dict = Depends(deps.get_current_active_user)
):
    """
    获取异常日志列表，支持多条件筛选
    """
    query = db.query(ExceptionLog)
    
    # 应用筛选条件
    if exception_type:
        query = query.filter(ExceptionLog.exception_type == exception_type)
    if exception_level:
        query = query.filter(ExceptionLog.exception_level == exception_level)
    if status:
        query = query.filter(ExceptionLog.status == status)
    if drone_id:
        query = query.filter(ExceptionLog.drone_id == drone_id)
    if task_id:
        query = query.filter(ExceptionLog.task_id == task_id)
    if responsible_user_id:
        query = query.filter(ExceptionLog.responsible_user_id == responsible_user_id)
    if start_time:
        query = query.filter(ExceptionLog.created_at >= start_time)
    if end_time:
        query = query.filter(ExceptionLog.created_at <= end_time)
    
    # 获取总数
    total = query.count()
    
    # 分页查询 - 只加载必要字段，避免直接返回关联对象
    exception_logs = query.offset(skip).limit(limit).all()
    
    # 将数据库模型转换为Pydantic模型可接受的格式
    response_data = []
    for log in exception_logs:
        # 创建一个字典，只包含基本字段，避免直接访问关联对象
        log_dict = {
            "id": log.id,
            "exception_type": log.exception_type,
            "exception_level": log.exception_level,
            "title": log.title,
            "description": log.description,
            "drone_id": log.drone_id,
            "task_id": log.task_id,
            "detection_log_id": log.detection_log_id,
            "location": log.location,
            "responsible_user_id": log.responsible_user_id,
            "status": log.status,
            "resolution_description": log.resolution_description,
            "created_at": log.created_at,
            "updated_at": log.updated_at,
            "resolution_time": log.resolution_time,
            # 关联字段设置为None，避免懒加载问题
            "responsible_user": None,
            "drone": None,
            "task": None
        }
        
        response_data.append(log_dict)
    
    return ExceptionLogListResponse(data=response_data, total=total)


@router.get("{exception_log_id}", response_model=ExceptionLogResponse, summary="获取异常日志详情")
def get_exception_log(
    exception_log_id: int,
    db: Session = Depends(deps.get_db),
    current_user: dict = Depends(deps.get_current_active_user)
):
    """
    根据ID获取异常日志详情
    """
    exception_log = db.query(ExceptionLog).filter(ExceptionLog.id == exception_log_id).first()
    if not exception_log:
        raise HTTPException(status_code=404, detail="异常日志不存在")
    
    # 将数据库模型转换为Pydantic可接受的格式
    log_dict = {
        "id": exception_log.id,
        "exception_type": exception_log.exception_type,
        "exception_level": exception_log.exception_level,
        "title": exception_log.title,
        "description": exception_log.description,
        "drone_id": exception_log.drone_id,
        "task_id": exception_log.task_id,
        "detection_log_id": exception_log.detection_log_id,
        "location": exception_log.location,
        "responsible_user_id": exception_log.responsible_user_id,
        "status": exception_log.status,
        "resolution_description": exception_log.resolution_description,
        "created_at": exception_log.created_at,
        "updated_at": exception_log.updated_at,
        "resolution_time": exception_log.resolution_time,
        # 关联字段设置为None，避免懒加载问题
        "responsible_user": None,
        "drone": None,
        "task": None
    }
    
    return log_dict


@router.put("{exception_log_id}", response_model=ExceptionLogResponse, summary="更新异常日志")
def update_exception_log(
    exception_log_id: int,
    exception_log_update: ExceptionLogUpdate,
    db: Session = Depends(deps.get_db),
    current_user: dict = Depends(deps.get_current_active_user)
):
    """
    更新异常日志，主要用于更新处理状态和责任人信息
    """
    exception_log = db.query(ExceptionLog).filter(ExceptionLog.id == exception_log_id).first()
    if not exception_log:
        raise HTTPException(status_code=404, detail="异常日志不存在")
    
    update_data = exception_log_update.model_dump(exclude_unset=True)
    
    # 如果状态变为已解决，更新解决时间
    if update_data.get("status") == "resolved" and exception_log.status != "resolved":
        update_data["resolution_time"] = datetime.utcnow()
    
    # 更新字段
    for field, value in update_data.items():
        setattr(exception_log, field, value)
    
    db.commit()
    db.refresh(exception_log)
    
    # 将数据库模型转换为Pydantic可接受的格式
    log_dict = {
        "id": exception_log.id,
        "exception_type": exception_log.exception_type,
        "exception_level": exception_log.exception_level,
        "title": exception_log.title,
        "description": exception_log.description,
        "drone_id": exception_log.drone_id,
        "task_id": exception_log.task_id,
        "detection_log_id": exception_log.detection_log_id,
        "location": exception_log.location,
        "responsible_user_id": exception_log.responsible_user_id,
        "status": exception_log.status,
        "resolution_description": exception_log.resolution_description,
        "created_at": exception_log.created_at,
        "updated_at": exception_log.updated_at,
        "resolution_time": exception_log.resolution_time,
        # 关联字段设置为None，避免懒加载问题
        "responsible_user": None,
        "drone": None,
        "task": None
    }
    
    return log_dict


@router.delete("/{exception_log_id}", summary="删除异常日志")
def delete_exception_log(
    exception_log_id: int,
    db: Session = Depends(deps.get_db),
    current_user: dict = Depends(deps.get_current_active_user)
):
    """
    删除异常日志
    """
    exception_log = db.query(ExceptionLog).filter(ExceptionLog.id == exception_log_id).first()
    if not exception_log:
        raise HTTPException(status_code=404, detail="异常日志不存在")
    
    db.delete(exception_log)
    db.commit()
    return {"message": "异常日志删除成功"}


@router.get("/statistics/overview", summary="获取异常日志统计概览")
def get_exception_log_statistics(
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    db: Session = Depends(deps.get_db),
    current_user: dict = Depends(deps.get_current_active_user)
):
    """
    获取异常日志的统计概览信息
    """
    query = db.query(ExceptionLog)
    
    # 时间范围筛选
    if start_date:
        query = query.filter(ExceptionLog.created_at >= start_date)
    if end_date:
        query = query.filter(ExceptionLog.created_at <= end_date)
    
    # 按异常类型统计
    type_statistics = db.query(
        ExceptionLog.exception_type,
        db_func.count(ExceptionLog.id)
    ).filter(query.whereclause).group_by(ExceptionLog.exception_type).all()
    
    # 按异常级别统计
    level_statistics = db.query(
        ExceptionLog.exception_level,
        db_func.count(ExceptionLog.id)
    ).filter(query.whereclause).group_by(ExceptionLog.exception_level).all()
    
    # 按处理状态统计
    status_statistics = db.query(
        ExceptionLog.status,
        db_func.count(ExceptionLog.id)
    ).filter(query.whereclause).group_by(ExceptionLog.status).all()
    
    return {
        "total_count": query.count(),
        "type_statistics": dict(type_statistics),
        "level_statistics": dict(level_statistics),
        "status_statistics": dict(status_statistics)
    }